<template>
  <div class="report-time-range-picker">
    <el-form-item label="时间范围" required>
      <div class="time-filter-container">
        <div class="time-header">
          <div class="time-header-left">
            <el-icon><Timer /></el-icon>
            <span>时间范围设置</span>
          </div>
          <el-button
            link
            type="primary"
            class="time-header-toggle"
            @click="toggleCollapse"
          >
            <el-icon v-if="isCollapsed"><ArrowDown /></el-icon>
            <el-icon v-else><ArrowUp /></el-icon>
            <span>{{ isCollapsed ? '展开设置' : '折叠设置' }}</span>
          </el-button>
        </div>

        <transition name="time-collapse">
          <div v-if="!isCollapsed">
            <el-radio-group 
              v-model="timeRangeType" 
              @change="handleTimeRangeChange"
              class="time-range-group"
            >
              <el-radio label="all" class="time-radio">
                <div class="radio-item">
                  <el-icon><Files /></el-icon>
                  <span>全部</span>
                  <el-tooltip content="查询所有历史数据，不限制时间范围" placement="top">
                    <el-icon class="help-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
              
              <el-radio label="yesterday" class="time-radio">
                <div class="radio-item">
                  <el-icon><Clock /></el-icon>
                  <span>昨天</span>
                  <el-tooltip content="查询昨天的数据" placement="top">
                    <el-icon class="help-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
              
              <el-radio label="recent" class="time-radio">
                <div class="radio-item">
                  <el-icon><Clock /></el-icon>
                  <span>最近7天</span>
                  <el-tooltip content="查询最近7天的数据" placement="top">
                    <el-icon class="help-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
              
              <el-radio label="last_month" class="time-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>上月</span>
                  <el-tooltip content="查询上月的完整数据" placement="top">
                    <el-icon class="help-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
              
              <el-radio label="custom" class="time-radio">
                <div class="radio-item">
                  <el-icon><Calendar /></el-icon>
                  <span>自定义</span>
                  <el-tooltip content="自定义时间范围" placement="top">
                    <el-icon class="help-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
            </el-radio-group>
            
            <div v-if="timeRangeType === 'custom'" class="custom-time-picker">
              <el-form-item label="选择时间范围" class="time-range-item">
                <el-date-picker
                  v-model="customTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :shortcuts="datePickerShortcuts"
                  @change="handleCustomTimeChange"
                  popper-class="report-time-range-picker__popper"
                  class="time-picker"
                />
              </el-form-item>
            </div>

            <div v-if="timeRangeType === 'custom'" class="quick-time-ranges">
              <div class="quick-header">
                <span>快捷选择</span>
              </div>
              <div class="quick-buttons">
                <el-button 
                  v-for="shortcut in quickTimeShortcuts" 
                  :key="shortcut.label"
                  size="small"
                  @click="applyQuickTime(shortcut)"
                >
                  {{ shortcut.label }}
                </el-button>
              </div>
            </div>
          </div>
        </transition>

        <div class="time-preview">
          <div class="preview-header">
            <el-icon><View /></el-icon>
            <span>当前时间设置</span>
          </div>
          <div class="preview-content">
            <el-tag 
              :type="getTimePreviewType()" 
              size="small" 
              class="time-tag"
            >
              <el-icon><Timer /></el-icon>
              {{ getTimePreviewText() }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-form-item>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { 
  Files, Clock, Calendar, QuestionFilled, View, Timer, ArrowDown, ArrowUp
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      time_range_type: 'all',
      time_start: null,
      time_end: null
    })
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const timeRangeType = ref('all')
const customTimeRange = ref([])
// 默认折叠，仅展示当前时间设置，用户需要时再展开
const isCollapsed = ref(true)

const datePickerShortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '昨天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      end.setTime(end.getTime() - 3600 * 1000 * 24)
      start.setHours(0, 0, 0, 0)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '本月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '上月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      end.setMonth(end.getMonth() - 1)
      start.setDate(1)
      end.setDate(new Date(end.getFullYear(), end.getMonth() + 1, 0).getDate())
      start.setHours(0, 0, 0, 0)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
]

const quickTimeShortcuts = [
  {
    label: '最近1小时',
    value: 1,
    unit: 'hours'
  },
  {
    label: '最近6小时',
    value: 6,
    unit: 'hours'
  },
  {
    label: '最近24小时',
    value: 24,
    unit: 'hours'
  },
  {
    label: '最近3天',
    value: 3,
    unit: 'days'
  },
  {
    label: '最近7天',
    value: 7,
    unit: 'days'
  },
  {
    label: '最近14天',
    value: 14,
    unit: 'days'
  }
]

const formatDateTime = (date) => {
  if (!date) return null
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const handleTimeRangeChange = () => {
  let timeFilter = {}
  if (timeRangeType.value === 'all') {
    timeFilter = {
      time_range_type: 'all',
      time_start: null,
      time_end: null
    }
  } else if (timeRangeType.value === 'yesterday') {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 1)
    start.setHours(0, 0, 0, 0)
    end.setDate(end.getDate() - 1)
    end.setHours(23, 59, 59, 999)
    timeFilter = {
      time_range_type: 'yesterday',
      time_start: formatDateTime(start),
      time_end: formatDateTime(end)
    }
  } else if (timeRangeType.value === 'recent') {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 7)
    timeFilter = {
      time_range_type: 'recent',
      time_start: formatDateTime(start),
      time_end: formatDateTime(end)
    }
  } else if (timeRangeType.value === 'last_month') {
    const end = new Date()
    const start = new Date()
    start.setMonth(start.getMonth() - 1)
    start.setDate(1)
    start.setHours(0, 0, 0, 0)
    end.setDate(1)
    end.setDate(end.getDate() - 1)
    end.setHours(23, 59, 59, 999)
    timeFilter = {
      time_range_type: 'last_month',
      time_start: formatDateTime(start),
      time_end: formatDateTime(end)
    }
  } else if (timeRangeType.value === 'custom') {
    if (customTimeRange.value && customTimeRange.value.length === 2) {
      timeFilter = {
        time_range_type: 'custom',
        time_start: customTimeRange.value[0],
        time_end: customTimeRange.value[1]
      }
    } else {
      timeFilter = {
        time_range_type: 'custom',
        time_start: null,
        time_end: null
      }
    }
  }
  emit('update:modelValue', timeFilter)
  emit('change', timeFilter)
}

const handleCustomTimeChange = () => {
  handleTimeRangeChange()
}

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

const applyQuickTime = (shortcut) => {
  const end = new Date()
  const start = new Date()
  if (shortcut.type === 'yesterday') {
    start.setDate(start.getDate() - 1)
    start.setHours(0, 0, 0, 0)
    end.setDate(end.getDate() - 1)
    end.setHours(23, 59, 59, 999)
  } else if (shortcut.type === 'last_month') {
    start.setMonth(start.getMonth() - 1)
    start.setDate(1)
    start.setHours(0, 0, 0, 0)
    end.setDate(1)
    end.setDate(end.getDate() - 1)
    end.setHours(23, 59, 59, 999)
  } else if (shortcut.unit === 'hours') {
    start.setTime(start.getTime() - 3600 * 1000 * shortcut.value)
  } else if (shortcut.unit === 'days') {
    start.setDate(start.getDate() - shortcut.value)
  }
  customTimeRange.value = [formatDateTime(start), formatDateTime(end)]
  handleTimeRangeChange()
}

const getTimePreviewText = () => {
  switch (timeRangeType.value) {
    case 'all':
      return '全部'
    case 'yesterday':
      return '昨天'
    case 'recent':
      return '最近7天'
    case 'last_month':
      return '上月'
    case 'custom':
      if (customTimeRange.value && customTimeRange.value.length === 2) {
        return `${customTimeRange.value[0]} 至 ${customTimeRange.value[1]}`
      }
      return '请选择时间范围'
    default:
      return '未设置'
  }
}

const getTimePreviewType = () => {
  switch (timeRangeType.value) {
    case 'all':
      return 'info'
    case 'yesterday':
    case 'recent':
    case 'last_month':
      return 'success'
    case 'custom':
      if (customTimeRange.value && customTimeRange.value.length === 2) {
        return 'warning'
      }
      return 'danger'
    default:
      return 'info'
  }
}

let isUpdatingFromProps = false

watch(() => props.modelValue, (newValue) => {
  if (newValue && !isUpdatingFromProps) {
    isUpdatingFromProps = true
    try {
      const newType = newValue.time_range_type || 'all'
      if (timeRangeType.value !== newType) {
        timeRangeType.value = newType
      }
      if (newType === 'custom' && newValue.time_start && newValue.time_end) {
        const newRange = [newValue.time_start, newValue.time_end]
        if (JSON.stringify(customTimeRange.value) !== JSON.stringify(newRange)) {
          customTimeRange.value = newRange
        }
      } else if (newType !== 'custom' && customTimeRange.value.length > 0) {
        customTimeRange.value = []
      }
    } finally {
      setTimeout(() => {
        isUpdatingFromProps = false
      }, 0)
    }
  }
}, { immediate: true, deep: true })

watch([timeRangeType, customTimeRange], () => {
  if (!isUpdatingFromProps) {
    handleTimeRangeChange()
  }
}, { deep: true })

defineExpose({
  getTimeRangeType: () => timeRangeType.value,
  getCustomTimeRange: () => customTimeRange.value,
  setTimeRangeType: (type) => {
    timeRangeType.value = type
    handleTimeRangeChange()
  },
  setCustomTimeRange: (range) => {
    customTimeRange.value = [...range]
    handleTimeRangeChange()
  }
})
</script>

<style scoped>
.report-time-range-picker {
  margin-bottom: 16px;
}

.time-filter-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.time-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.time-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.time-header-toggle {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.time-range-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.time-radio {
  flex: 1 1 calc(50% - 12px);
  margin: 0 !important;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: white;
  transition: all 0.3s ease;
}

.time-radio:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.time-radio.is-checked {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  cursor: help;
}

.custom-time-picker {
  padding: 16px;
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 16px;
}

.time-range-item {
  margin: 0 !important;
}

.time-picker {
  width: 100%;
}

.time-preview {
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
  margin-bottom: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.preview-content {
  display: flex;
  align-items: center;
}

.time-tag {
  margin: 0 !important;
}

.quick-time-ranges {
  padding: 12px;
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.quick-header {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.time-collapse-enter-active,
.time-collapse-leave-active {
  transition: all 0.2s ease;
}

.time-collapse-enter-from,
.time-collapse-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}

@media (max-width: 768px) {
  .time-range-group {
    flex-direction: column;
    gap: 8px;
  }

  .time-radio {
    padding: 8px;
    flex: 1 1 100%;
  }

  .quick-buttons {
    gap: 6px;
  }
}

.time-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.time-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
}

:global(.report-time-range-picker__popper) {
  z-index: 4000 !important;
}
</style>
